#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import re

bbox_count_list_path = r'/rootfs/media/kasim/Data1/data/FaceVideo/bbox_count_list.txt'
bbox_list_path = r'/rootfs/media/kasim/Data1/data/FaceVideo/bbox_list.txt'
out_path = r'/rootfs/media/kasim/Data1/data/FaceVideo'
out_file_box_list_name = r'file_bbox_list.txt'


def main():
    if not os.path.exists(out_path):
        os.makedirs(out_path)
    os.system('chmod a+wr {}'.format(out_path))

    pattern = re.compile(r'F([-\d]+)B([-\d]+)')

    out_file_bbox_path = os.path.join(out_path, out_file_box_list_name)
    out_file_bbox = open(out_file_bbox_path, 'w')

    file_bbox_map = {}
    dir_frame_bbox_map = {}
    with open(bbox_count_list_path, 'r') as bbox_count_file:
        with open(bbox_list_path, 'r') as bbox_file:
            for line in bbox_count_file.readlines():
                lines = line.strip().split(',')
                file_dir = os.path.splitext(lines[0])[0]

                frame_bbox_map = dir_frame_bbox_map.get(file_dir, None)
                if frame_bbox_map is None:
                    frame_bbox_map = {}
                    dir_frame_bbox_map[file_dir] = frame_bbox_map
                bbox_count = int(lines[1])
                for _ in range(bbox_count):
                    bbox_infos = bbox_file.readline()
                    bbox_infos = bbox_infos.strip().split()
                    file_name = bbox_infos[0]

                    fr_num, b_num = map(int, pattern.search(file_name).groups())

                    file_path = os.path.join(file_dir, file_name)
                    bbox_info1 = bbox_infos[1]
                    bbox_info2 = bbox_infos[2]

                    bboxes = frame_bbox_map.get(fr_num, None)
                    if bboxes is None:
                        bboxes = [[], []]
                        frame_bbox_map[fr_num] = bboxes

                    bboxes[0].append(bbox_info1)
                    bboxes[1].append(bbox_info2)
                    file_bbox_map[file_path] = [bbox_info1, bbox_info2]

    file_names = list(file_bbox_map.keys())
    file_names.sort()
    for file_name in file_names:
        bboxes = file_bbox_map.get(file_name, None)
        if bboxes is None:
            continue
        out_info_str = '{} {} {}\n'.format(file_name, bboxes[0], bboxes[1])
        out_file_bbox.write(out_info_str)

    out_file_bbox.close()
    os.system('chmod a+wr {}'.format(out_file_bbox_path))

    print('finish!!!!')


if __name__ == '__main__':
    main()
